package it.nm.unipicontrol.test.ui;

import it.nm.unipicontrol.gateway.UniPIGateway;
import it.nm.unipicontrol.ui.RelayButton;

import java.awt.BorderLayout;
import java.awt.EventQueue;
import java.awt.FlowLayout;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.FileInputStream;
import java.net.URL;
import java.util.Timer;
import java.util.TimerTask;
import java.util.logging.Level;
import java.util.logging.LogManager;
import java.util.logging.Logger;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;

public class UniPIControlTestUI {

	private JFrame frmUnipiControlDesktop;
	
    private static final Logger logger = Logger.getLogger(UniPIControlTestUI.class.getName());
    
    private PollingTimer polling;

	/**
	 * Launch the application.
	 */
	public static void main(String[] args) {
		EventQueue.invokeLater(new Runnable() {
			public void run() {
				try {
					
					URL url = UniPIControlTestUI.class.getResource("logging.properties");
					LogManager.getLogManager().readConfiguration(new FileInputStream(url.getPath()));
					logger.log(Level.INFO, "Start UNIPI DesktopClient");
					
					UniPIControlTestUI window = new UniPIControlTestUI();
					window.frmUnipiControlDesktop.setVisible(true);
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		});
	}

	/**
	 * Create the application.
	 */
	public UniPIControlTestUI() {
		
		polling = new PollingTimer(true);
		initialize();

	}

	/**
	 * Initialize the contents of the frame.
	 */
	private void initialize() {
		frmUnipiControlDesktop = new JFrame();
		frmUnipiControlDesktop.setTitle("UniPI Control Desktop Client");
		frmUnipiControlDesktop.setBounds(100, 100, 456, 572);
		frmUnipiControlDesktop.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		
		JPanel mainPanel = new JPanel();
		frmUnipiControlDesktop.getContentPane().add(mainPanel, BorderLayout.CENTER);
		mainPanel.setLayout(new BorderLayout(0, 0));
		
		JPanel relaisPanel = new JPanel();
		mainPanel.add(relaisPanel, BorderLayout.NORTH);
		GridBagLayout gbl_relaisPanel = new GridBagLayout();
		gbl_relaisPanel.columnWidths = new int[] {100, 0, 0, 0, 100};
		gbl_relaisPanel.rowHeights = new int[]{3, 0, 0, 0, 0, 0, 0, 0, 0};
		gbl_relaisPanel.columnWeights = new double[]{0.0, 0.0, 0.0, 0.0, Double.MIN_VALUE};
		gbl_relaisPanel.rowWeights = new double[]{0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, Double.MIN_VALUE};
		relaisPanel.setLayout(gbl_relaisPanel);
		
		JLabel lblRelay = new JLabel("Relay 1");
		GridBagConstraints gbc_lblRelay = new GridBagConstraints();
		gbc_lblRelay.insets = new Insets(0, 0, 5, 5);
		gbc_lblRelay.gridx = 0;
		gbc_lblRelay.gridy = 0;
		relaisPanel.add(lblRelay, gbc_lblRelay);
		
		RelayButton relay1Button = new RelayButton();
		relay1Button.setRelay(1);
		GridBagConstraints gbc_relay1Button = new GridBagConstraints();
		gbc_relay1Button.insets = new Insets(0, 0, 5, 0);
		gbc_relay1Button.gridx = 3;
		gbc_relay1Button.gridy = 0;
		relaisPanel.add(relay1Button, gbc_relay1Button);
		
		JLabel lblRelay_1 = new JLabel("Relay 2");
		GridBagConstraints gbc_lblRelay_1 = new GridBagConstraints();
		gbc_lblRelay_1.insets = new Insets(0, 0, 5, 5);
		gbc_lblRelay_1.gridx = 0;
		gbc_lblRelay_1.gridy = 1;
		relaisPanel.add(lblRelay_1, gbc_lblRelay_1);
		
		RelayButton relay2Button = new RelayButton();
		relay2Button.setRelay(2);
		GridBagConstraints gbc_relay2Button = new GridBagConstraints();
		gbc_relay2Button.insets = new Insets(0, 0, 5, 0);
		gbc_relay2Button.gridx = 3;
		gbc_relay2Button.gridy = 1;
		relaisPanel.add(relay2Button, gbc_relay2Button);
		
		JLabel lblRelay_2 = new JLabel("Relay 3");
		GridBagConstraints gbc_lblRelay_2 = new GridBagConstraints();
		gbc_lblRelay_2.insets = new Insets(0, 0, 5, 5);
		gbc_lblRelay_2.gridx = 0;
		gbc_lblRelay_2.gridy = 2;
		relaisPanel.add(lblRelay_2, gbc_lblRelay_2);
		
		RelayButton relay3Button = new RelayButton();
		relay3Button.setRelay(3);
		GridBagConstraints gbc_relay3Button = new GridBagConstraints();
		gbc_relay3Button.insets = new Insets(0, 0, 5, 0);
		gbc_relay3Button.gridx = 3;
		gbc_relay3Button.gridy = 2;
		relaisPanel.add(relay3Button, gbc_relay3Button);
		
		JLabel lblRelay_3 = new JLabel("Relay 4");
		GridBagConstraints gbc_lblRelay_3 = new GridBagConstraints();
		gbc_lblRelay_3.insets = new Insets(0, 0, 5, 5);
		gbc_lblRelay_3.gridx = 0;
		gbc_lblRelay_3.gridy = 3;
		relaisPanel.add(lblRelay_3, gbc_lblRelay_3);
		
		RelayButton relay4Button = new RelayButton();
		relay4Button.setRelay(4);
		GridBagConstraints gbc_relay4Button = new GridBagConstraints();
		gbc_relay4Button.insets = new Insets(0, 0, 5, 0);
		gbc_relay4Button.gridx = 3;
		gbc_relay4Button.gridy = 3;
		relaisPanel.add(relay4Button, gbc_relay4Button);
		
		JLabel lblRelay_4 = new JLabel("Relay 5");
		GridBagConstraints gbc_lblRelay_4 = new GridBagConstraints();
		gbc_lblRelay_4.insets = new Insets(0, 0, 5, 5);
		gbc_lblRelay_4.gridx = 0;
		gbc_lblRelay_4.gridy = 4;
		relaisPanel.add(lblRelay_4, gbc_lblRelay_4);
		
		RelayButton relay5Button = new RelayButton();
		relay5Button.setRelay(5);
		GridBagConstraints gbc_relay5Button = new GridBagConstraints();
		gbc_relay5Button.insets = new Insets(0, 0, 5, 0);
		gbc_relay5Button.gridx = 3;
		gbc_relay5Button.gridy = 4;
		relaisPanel.add(relay5Button, gbc_relay5Button);
		
		JLabel lblRelay_5 = new JLabel("Relay 6");
		GridBagConstraints gbc_lblRelay_5 = new GridBagConstraints();
		gbc_lblRelay_5.insets = new Insets(0, 0, 5, 5);
		gbc_lblRelay_5.gridx = 0;
		gbc_lblRelay_5.gridy = 5;
		relaisPanel.add(lblRelay_5, gbc_lblRelay_5);
		
		RelayButton relay6Button = new RelayButton();
		relay6Button.setRelay(6);
		GridBagConstraints gbc_relay6Button = new GridBagConstraints();
		gbc_relay6Button.insets = new Insets(0, 0, 5, 0);
		gbc_relay6Button.gridx = 3;
		gbc_relay6Button.gridy = 5;
		relaisPanel.add(relay6Button, gbc_relay6Button);
		
		JLabel lblRelay_6 = new JLabel("Relay7");
		GridBagConstraints gbc_lblRelay_6 = new GridBagConstraints();
		gbc_lblRelay_6.insets = new Insets(0, 0, 5, 5);
		gbc_lblRelay_6.gridx = 0;
		gbc_lblRelay_6.gridy = 6;
		relaisPanel.add(lblRelay_6, gbc_lblRelay_6);
		
		RelayButton relay7Button = new RelayButton();
		relay7Button.setRelay(7);
		GridBagConstraints gbc_relay7Button = new GridBagConstraints();
		gbc_relay7Button.insets = new Insets(0, 0, 5, 0);
		gbc_relay7Button.gridx = 3;
		gbc_relay7Button.gridy = 6;
		relaisPanel.add(relay7Button, gbc_relay7Button);
		
		JLabel lblRelay_7 = new JLabel("Relay 8");
		GridBagConstraints gbc_lblRelay_7 = new GridBagConstraints();
		gbc_lblRelay_7.insets = new Insets(0, 0, 0, 5);
		gbc_lblRelay_7.gridx = 0;
		gbc_lblRelay_7.gridy = 7;
		relaisPanel.add(lblRelay_7, gbc_lblRelay_7);
		
		RelayButton relay8Button = new RelayButton();

		relay8Button.setRelay(8);
		GridBagConstraints gbc_relay8Button = new GridBagConstraints();
		gbc_relay8Button.gridx = 3;
		gbc_relay8Button.gridy = 7;
		relaisPanel.add(relay8Button, gbc_relay8Button);
		
		JPanel temperaturePanel = new JPanel();
		mainPanel.add(temperaturePanel, BorderLayout.CENTER);
		GridBagLayout gbl_temperaturePanel = new GridBagLayout();
		gbl_temperaturePanel.columnWidths = new int[] {0, 0, 100, 0, 100};
		gbl_temperaturePanel.rowHeights = new int[]{0, 0, 0, 0, 0};
		gbl_temperaturePanel.columnWeights = new double[]{0.0, 0.0, Double.MIN_VALUE};
		gbl_temperaturePanel.rowWeights = new double[]{0.0, 0.0, 0.0, 0.0, Double.MIN_VALUE};
		temperaturePanel.setLayout(gbl_temperaturePanel);
		
		JLabel lblTemperature = new JLabel("Temperature");
		GridBagConstraints gbc_lblTemperature = new GridBagConstraints();
		gbc_lblTemperature.insets = new Insets(0, 0, 5, 5);
		gbc_lblTemperature.gridx = 0;
		gbc_lblTemperature.gridy = 1;
		temperaturePanel.add(lblTemperature, gbc_lblTemperature);
		
		JLabel lblNotInitialized = new JLabel("Not Initialized");
		GridBagConstraints gbc_lblNotInitialized = new GridBagConstraints();
		gbc_lblNotInitialized.insets = new Insets(0, 0, 5, 5);
		gbc_lblNotInitialized.gridx = 1;
		gbc_lblNotInitialized.gridy = 1;
		temperaturePanel.add(lblNotInitialized, gbc_lblNotInitialized);
		
		JPanel statusBar = new JPanel();
		mainPanel.add(statusBar, BorderLayout.SOUTH);
		statusBar.setLayout(new FlowLayout(FlowLayout.LEFT, 5, 5));
		
		JLabel statusLabel = new JLabel("Not Initialized");
		statusBar.add(statusLabel);
		
		final JButton pollingButton = new JButton("Start Polling");
		pollingButton.setEnabled(false);
		statusBar.add(pollingButton);

		
		final JButton connectionButton = new JButton("Initialize");
		statusBar.add(connectionButton);
		
		pollingButton.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				if (!polling.isRunning()) {
					polling = new PollingTimer(true);
					polling.scheduleAtFixedRate(new Polling(), 0, 1000);
					pollingButton.setText("Stop Polling");
					polling.setRunning(true);
					
				} else {
					polling.cancel();
					pollingButton.setText("Start Polling");
					polling.setRunning(false);
				}
			}
		});
		
		connectionButton.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				try {
					UniPIGateway.INSTANCE.connect();
					connectionButton.setText("connected!");
					connectionButton.setEnabled(false);
					pollingButton.setEnabled(true);
					
				} catch (Exception e1) {
					logger.log(Level.FINE, "error connecting to UniPi: "+e1.getMessage());
					e1.printStackTrace();
				}
			}
		});
	}

	private class PollingTimer extends Timer {
		
		private boolean running = false;

		public PollingTimer(boolean b) {
			super(b);
		}

		public boolean isRunning() {
			return running;
		}

		public void setRunning(boolean running) {
			this.running = running;
		}
		
	}
	
	private class Polling extends TimerTask {

		private final Logger plogger = Logger.getLogger(Polling.class.getName());
		
		@Override
		public void run() {
			try {
				plogger.log(Level.FINE, "polling UniPi...");
				UniPIGateway.INSTANCE.getState();
			} catch (Exception e) {
				plogger.log(Level.SEVERE,"error connecting to UniPI", e);
			}
		}
		
	    private void completeTask() {
	        try {
	            Thread.sleep(1000);
	        } catch (InterruptedException e) {
	        	plogger.log(Level.SEVERE,"error completeTask", e);
	        }
	    }
		
	}
	
}
